import { observable, action, extendObservable, isObservable,toJS } from "mobx";
import { WeaBrowser,WeaTools,WeaLocaleProvider} from "ecCom";
import { WeaForm, WeaInput } from "comsMobx";
import * as Api from "./../apis/receiveDoc"; 
import CommonStore from "./commonStore";
import * as conditions from "../constants/conditions";
import { message } from "antd";
const {getLabel} = WeaLocaleProvider;
export default class ReceiveDoc extends CommonStore {
  test = "接收公文";

  constructor() {
    super();
    this.pageName = "receiveDoc";
  }
  @observable menuType ="receiveDoc";

  @observable ifShowRejectForm = false;//拒收弹窗显隐
  @observable rejectForm = new WeaForm();
  @observable rejectFormCon = conditions.rejectCondt;

  @observable ifSendBackForm = false;//退回弹窗的显隐
  @observable sendBackForm = new WeaForm();
  @observable sendBackFormCon = conditions.sendBackCondt;

  /*
   *配置流程相关store
   */
  @observable setWfDiaForm = new WeaForm();
  @observable setWfDiaFormCon = "";
  @observable tableEditTitle = "";
  @observable tableEditCols = [];
  @observable tableEditDatas = [];
  //这几个加上setWfDiaForm可用于获取tableedit的cols和datas
  @observable chageFlag = "";
  @observable companyid = "";
  @observable sn = "";
  @observable	version ="";
  @observable workflowid= "";
  @observable ifShowSetWFDia = false;
  @observable ifShowTableEdit = false; //这个表示是否显示配置流程弹窗里的tableedit组件，仅在刚点击配置按钮后且并没有改动表单中任何值的时候才为false
  @observable ifShowLoadingAnimation = false; //表示配置流程弹窗中是否出现一个loading动画————一个用于表示loading新的tableedit的动画

  /**'
   * 创建流程store
   */
  @observable selTableIdOfcreateWF = "";
  @observable createWFsn = "";
  @observable createWfid = "";
  
  //创建流程弹窗
  @observable showCreatFlow = false;
  @observable selectRowId =[];//选择行的Id
  @observable flowListData = [];//流程列表数据

//流程列表数据
@action.bound getFlowList(officalType){
  const params = {officalType}
  Api.createChangeFlowList(params).then(data=>{
    if(data.api_status){
      if(data.datas.length > 0 && this.flowListData.length == 0){
        this.flowListData=[...this.flowListData,...data.datas]        
      }else if(data.datas.length > 0 && this.flowListData.length != 0){
        this.flowListData= [...this.flowListData,...data.datas];         
      }
      this.flowListData = this.deteleObject(toJS(this.flowListData))
    }
    
  })
}

  //新建流程
  @action.bound openCreatFlowWindow(workflowid,listName){
    const params = {
      ids:this.selectRowId.join(","),
      createWfid:workflowid,
      // ids:"1",
      // createWfid:"21484"
    }
    Api.getRequstId(params).then(data=>{
      if(data.status){
        if(this.menuType !="receiveDoc"){
          var formData = this.handworkForm.getFormParams();
          formData.Document_Attachments = this.fileId.Document_Attachments;
          formData.Document_Text = this.fileId.Document_Text;
          const info = {
            documentIdentifier:this.document_identifier,
            registrationProcessing :listName,
            receiveStatus : 1,
            ...formData ,
            receiveDocType:this.type,
          }
          Api.saveRegistrationFormData(info)
          this.initData({
            compParams: {
              viewcondition: 0,
              viewconditiondomkey: "state",
              menuType:this.menuType,
            }});
        }
        const width = screen.availWidth - 10;
        const height = screen.availHeight - 50;
        let szFeatures = "top=0,left=0,";
        szFeatures += "width=" + width + ",";
        szFeatures += "height=" + height + ",";
        szFeatures += "directories=no,status=yes,toolbar=no,location=no,";
        szFeatures += "menubar=no,scrollbars=yes,resizable=yes";
        window.open(data.url,"",szFeatures);
      }else{ 
        message.error(data.message);
      }
    }).catch( error =>{
      message.error(error)
    })
  }
//获取页面类型 并初始化页面
  @action.bound getMenuType(){
    Api.getMenuType().then(data=>{
      if(data.api_status){
        this.menuType = data.menuType;
      }
      this.initData({
        compParams: {
          viewcondition: 0,
          viewconditiondomkey: "state",
          menuType:this.menuType,
        }});
      })
    }


/*------------------------------- 收文登记-------------------*/

  //手工登记 
  @observable handworkForm = new WeaForm();//手工登记form
  @observable handwordCondition = [];
  @observable handworkShow = false; 

  @observable registProcessShow = false; //登记处理
  @observable fileId = {} //文件id
  @observable fileInfoArr = {
    Document_Attachments:[],
    Document_Text:[],
  } //文件信息

  @observable docId="";

  @observable type="0"; //type  0 代表手工登记的二级弹窗 1 智能登记二级弹窗 2 扫码登记

  //登记处理
  @observable receiveSmartShow = false ; 

  @observable isReceivecheck = false;
  @observable document_identifier = "";

  @action.bound setMobxState(params={}){
    Object.keys(params).forEach( v =>{
      this[v] = params[v]
    })
  }

  //处理手工登记form表单
  @action.bound setRegistrationForm(data){    
    this.handworkForm = new WeaForm();
    let file = [];
    const items = data.condition[0].items
    for(let i=0 ; i < data.condition[0].items.length ;i++){
      const item = items[i];
      if(item.conditionType.toUpperCase() == WeaTools.types.UPLOAD ){
        this.fileInfoArr[item.domkey[0]] = item.datas || [];
      }
      //为了美观 把附件放在最后
      if(item.domkey[0] == "Document_Attachments"){
        items.splice(i,1)
        file.push(item);
        i--;
      }
      //为了美观 把正文放在最后
      if(item.domkey[0] == "Document_Text"){
        items.splice(i,1)
        file.unshift(item);
        i--;
      }          
    }
    data.condition[0].items=[...data.condition[0].items,...file]
    this.handworkForm.initFormFields(toJS(data.condition));
    this.handwordCondition = data.condition; 
  }

  //登记保存
  @action.bound
  registSave(CreatFlow){
    let formData = this.handworkForm.getFormParams();
    formData.Document_Attachments = this.fileId.Document_Attachments;
    formData.Document_Text = this.fileId.Document_Text;
    const params = {...formData , receiveDocType:this.type,receiveStatus:"0"}
    Api.saveRegistrationFormData(params).then(data=>{
      if(data.api_status){
        //获取id 为创建流程所用
        this.secondDialogOncCancel();
        this.initData({
          compParams: {
            viewcondition: 0,
            viewconditiondomkey: "state",
            menuType:this.menuType,
          }});
        if(CreatFlow){
          this.selectRowId.push(data.message);
          this.document_identifier = data.documentIdentifier;
        }
      }
    })
  }

  //智能登记的时候显示上传文件信息
  @action.bound setFileInfo(type,ids,list,name){
    this.fileId[type] = ids.join(",");
    this.fileInfoArr[type] = list;
    if(name == "smartRegist"){
      let nameArr = [];
      list.map(item=>{
        nameArr.push(item.filename)
      })
      const value = nameArr.join(" ，")
      document.getElementById(type).value = value;
    }   
  }

  //智能登记 下一步
  @action.bound smartRegistration(){
    this.loading = true;
    const params={
      imageFileId:this.fileId.Document_Text,
      imageFileName:this.fileInfoArr.Document_Text[0].filename,
      attachmentIds:this.fileId.Document_Attachments,
    }
    Api.smartRegistration(params).then(data=>{
      this.loading = false;
      if(data.api_status){
        this.type = "1";
        this.setRegistrationForm(data)
        this.docId = data.message;
        this.receiveSmartShow = false;
        this.registProcessShow = true;
      }else{
        this.dialogOnCancel()
        message.error(getLabel("","文件转换失败"))
      }
    })
  }

  @action.bound secondDialogOncCancel(){
    this.registProcessShow = false ;
    this.clearFile()
    this.isReceivecheck = false; 
    this.selectRowId = [];
  }
  
  //点击查看
  @action.bound 
  getRegistrationFormData(){
    const params = {
      id:this.selectRowId.join(",")
    }
    Api.getRegistrationFormData(params).then(data=>{
      if(data.api_status){
        this.setRegistrationForm(data)
        this.docId = data.message;
        this.registProcessShow = true;
      }
    })
  }

  //登记处理
  @action.bound 
  nextTept(){
    this.handworkForm.validate().then(f => {   
      if (f.isValid) {
        this.type = "0" ;
        if(this.fileInfoArr.Document_Text[0].fileExtendName !="pdf"){
          this.getChangeWordToPdf();
        }
        this.registProcessShow = true;
        this.handworkShow =false;
      } else {
        f.showErrors();
      }
    })
  }

  //上一步
  @action.bound 
  previousTept(){
    if(this.type == "0" ){
      this.handworkShow = true;
    }else{
      this.receiveSmartShow = true;
    }
    this.registProcessShow = false;
  }

  //来文转收文
  @action.bound 
  forwardCommunication(){
    if(this.selectRowId.length > 0){
      this.showCreatFlow = true;
    }else{
      this.registSave(true)
      this.showCreatFlow = true;
    }
    this.registProcessShow = false;
  }

  //手工登记关闭
  @action.bound 
  handwordRegistOnCancel(){
    this.handworkShow = false;
    this.clearFile()
  }

  //智能登记关闭
  @action.bound 
  dialogOnCancel(){
    this.receiveSmartShow= false;
    this.clearFile()
  }

  //清除文件信息
  @action.bound 
  clearFile(){
    this.fieldId = {};
    this.fileInfoArr = {
      Document_Attachments:[],
      Document_Text:[],
    }
  }

  @action.bound 
  getChangeWordToPdf(){
    const params = {
      imageFileId : this.fileId.Document_Text,
    }
    Api.changeWordToPdf(params).then(data=>{
      if(data.api_status){
        this.docId = data.message;
      }else{
        message.error(data.message)
      }
    })
  }
  deteleObject(obj) {
    var uniques = [];
    var stringify = {};
    for (var i = 0; i < obj.length; i++) {
      var keys = Object.keys(obj[i]);
      keys.sort(function(a, b) {
        return (Number(a) - Number(b));
      });
      var str = '';
      for (var j = 0; j < keys.length; j++) {
        str += JSON.stringify(keys[j]);
        str += JSON.stringify(obj[i][keys[j]]);
      }
      if (!stringify.hasOwnProperty(str)) {
        uniques.push(obj[i]);
        stringify[str] = true;
      }
    }
    uniques = uniques;
    return uniques;
  }
  
  

}
